﻿using Dapper;
using Gx.Common.Core;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Gx.Dal.Extensions
{
    public static class DbContextConnectionExtensions
    {
        public static bool DeleteByIds<T, Tkey>(this IDbConnection conn, List<Tkey> ids, IDbTransaction trans = null)
        {
            string tableName = EntityHelper.GetTableName(typeof(T));
            bool result = false;
            //string query = string.Format("DELETE FROM {0} WHERE {1} = @id", TableName, PrimaryKey.Name);
            string query = string.Format("UPDATE {0} SET IsDeleted=1 WHERE Id in @ids", tableName);
            var parameters = new DynamicParameters();
            parameters.Add("@ids", ids);

            result = conn.Execute(query, parameters, trans) > 0;

            return result;
        }

        public static IEnumerable<T> GetListByWhere<T>(this IDbConnection conn, string condition, object param = null, IDbTransaction trans = null)
        {
            string tableName = EntityHelper.GetTableName(typeof(T));
            string where = string.IsNullOrWhiteSpace(condition) ? "" : " AND " + condition;
            string query = string.Format("SELECT * FROM {0} WITH(NOLOCK) WHERE IsDeleted=0 {1}", tableName, where);
            return conn.Query<T>(query, param, trans);
        }

        public static bool DeleteByWhere<T>(this IDbConnection conn, string condition, object param = null, IDbTransaction trans = null)
        {
            string tableName = EntityHelper.GetTableName(typeof(T));
            if (string.IsNullOrWhiteSpace(condition)) return false;
            string query = string.Format("UPDATE {0} SET IsDeleted=1 WHERE {1}", tableName, condition);

            var result = conn.Execute(query, param, trans) > 0;

            return result;
        }
    }
}
